package com.heba.greenmulu.user;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.diary.ItemDiaryImageObject;
import com.heba.bean.diary.ItemDiaryTagObject;
import com.heba.bean.product.ItemProductInfoObject;
import com.heba.bean.user.UserProductReviewObject;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.scan.ItemProductDetailActivity;
import com.heba.helper.DateHelper;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.view.FlowLayout;
import com.heba.view.MyRatingBarView;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户产品评价页面
 * Created by jason on 2020/3/13.
 */
public class UserProductReviewActivity extends BaseActivity {

    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<UserProductReviewObject> list;
    private TextView alertLB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview);
        initTopbar();
        findViewById();
        initView();
        getProductCommentListData();
    }

    @Override
    protected void findViewById() {
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
        alertLB = findViewById(R.id.alertLB);
        alertLB.setText(R.string.no_pro_com);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.mine_product_review));

        list = new ArrayList<>();

        recycleAdapter = new QuickAdapter<UserProductReviewObject>(list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_user_product_review;
            }

            @Override
            public void convert(VH holder, UserProductReviewObject data, int position) {
                holder.setText(R.id.tv_desc, CommonUtils.getDecodeText(data.getContent()));
                holder.setText(R.id.tv_time, DateHelper.transferDateString(UserProductReviewActivity.this, data.getTimeCreated()));

                /**
                 * 显示评论图片
                 */
                FlowLayout fl_photo_view = holder.getView(R.id.fl_photo_view);
                updateCommentImageView(fl_photo_view, data.getImageList());

                /**
                 * 显示话题标签
                 */
                FlowLayout fl_tag_view = holder.getView(R.id.fl_tag_view);
                updateTagFlowView(fl_tag_view, data.getTalkList());

                /**
                 * 显示产品信息
                 */
                View view_product = holder.getView(R.id.view_product);
                view_product.setVisibility(View.GONE);
                if (!data.getProduct().isEmpty()) {
                    view_product.setVisibility(View.VISIBLE);
                    ItemProductInfoObject infoObject = data.getProduct().get(0);
                    GlideUtil.loadImageWithDefaultPlaceHolder(UserProductReviewActivity.this, infoObject.getIcon(), holder.getView(R.id.iv_product));
                    holder.setText(R.id.tv_product, infoObject.getBrandName());
                    holder.setText(R.id.tv_content, infoObject.getProductName());
                    holder.setText(R.id.tv_weight, String.format(getResources().getString(R.string.per_serving_size), infoObject.
                            getPackageSize(), infoObject.getPackageUnit(), CommonUtils.subZeroAndDot(infoObject.getServingSize()), infoObject.getServingSizeUnit()));
                    MyRatingBarView rb_view = holder.getView(R.id.rb_view);
                    rb_view.setStar(data.getStar());

                    /**
                     * 跳轉產品詳情頁
                     */
                    view_product.setOnClickListener(v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString(CommonConfig.PRODUCT_ID, infoObject.getProductID());
                        openActivity(ItemProductDetailActivity.class, bundle);
                    });

                    /**
                     * 跳轉日記詳情頁
                     */
                    holder.itemView.setOnClickListener(v -> {
                        Bundle bundle = new Bundle();
                        bundle.putInt(CommonConfig.TYPE, 1);
                        bundle.putString(CommonConfig.DIARY_ID, data.getDiaryID());
                        openActivity(UserDiaryListActivity.class, bundle);
                    });
                }

            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            getProductCommentListData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getProductCommentListData();
        });
    }

    /**
     * 更新产品评论图片view
     */
    private void updateCommentImageView(FlowLayout flowLayout, List<ItemDiaryImageObject> imageObjectList) {
        flowLayout.removeAllViews();

        int photoWidth = (ScreenWidth - DensityUtils.dip2px(this, (float) 30.5)) / 3;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(photoWidth, photoWidth);
        params.rightMargin = DensityUtils.dip2px(this, 5);
        params.bottomMargin = DensityUtils.dip2px(this, 5);
        if (!imageObjectList.isEmpty()) {
            for (int i = 0; i < imageObjectList.size(); i++) {
                ItemDiaryImageObject imageObject = imageObjectList.get(i);
                View imageView = LayoutInflater.from(this).inflate(R.layout.item_comment_round_image, null);
                ImageView img_photo = imageView.findViewById(R.id.img_photo);
                imageView.setLayoutParams(params);
                GlideUtil.loadImageWithDefaultPlaceHolder(this, imageObject.getImageUrl(), img_photo);

                flowLayout.addView(imageView);
            }
        }
    }

    /**
     * 更新流式佈局
     *
     * @param flowLayout
     * @param tags
     */
    private void updateTagFlowView(FlowLayout flowLayout, List<ItemDiaryTagObject> tags) {
        flowLayout.removeAllViews();

        if (tags == null)
            return;

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(this, 20));
        params.rightMargin = DensityUtils.dip2px(this, 8);
        params.bottomMargin = DensityUtils.dip2px(this, 3);
        for (int i = 0; i < tags.size(); i++) {
            flowLayout.addView(updateFlowRowView(tags.get(i)), params);
        }
    }

    /**
     * 添加item佈局
     */
    private View updateFlowRowView(ItemDiaryTagObject object) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_tag_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getContent());
        return view;
    }

    /**
     * 获取用户产品评价列表
     */
    private void getProductCommentListData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/User/ProductEvaluation", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<UserProductReviewObject> productReviewObjects = new Gson().fromJson(array.toString(), new TypeToken<List<UserProductReviewObject>>() {
                                }.getType());
                                list.addAll(list.size(), productReviewObjects);
                                alertLB.setVisibility(View.GONE);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                alertLB.setVisibility(View.VISIBLE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }
}
